#region Using

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Configuration.Provider;
using System.Web.Configuration;

#endregion

namespace BlogEngine.Core.Provider
{
	/// <summary>
	/// The proxy class for communication between
	/// the business objects and the providers.
	/// </summary>
	public static class BlogService
	{
		private static BlogProviderBase _provider;
		private static ProviderCollection _providers;
		private static object _lock = new object();

		/// <summary>
		/// Gets the current provider.
		/// </summary>
		public static BlogProviderBase Provider
		{
			get
			{
				LoadProviders();
				return _provider;
			}
		}

		/// <summary>
		/// Gets a collection of all registered providers.
		/// </summary>
		public static ProviderCollection Providers
		{
			get
			{
				LoadProviders();
				return _providers;
			}
		}

		/// <summary>
		/// Load the providers from the web.config.
		/// </summary>
		private static void LoadProviders()
		{
			// Avoid claiming lock if providers are already loaded
			if (_provider == null)
			{
				lock (_lock)
				{
					// Do this again to make sure _provider is still null
					if (_provider == null)
					{
						// Get a reference to the <blogProvider> section
						BlogProviderSection section = (BlogProviderSection)WebConfigurationManager.GetSection("BlogEngine/blogProvider2");

						// Load registered providers and point _provider
						// to the default provider
						_providers = new ProviderCollection();
						ProvidersHelper.InstantiateProviders(section.Providers, _providers, typeof(BlogProviderBase));
						_provider = (BlogProviderBase)_providers[section.DefaultProvider];

						if (_provider == null)
							throw new ProviderException("Unable to load default BlogProvider");
					}
				}
			}
		}

	}
}
